package com.unitech.drinks.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.unitech.drinks.exception.BusinessErrorCode;
import com.unitech.drinks.exception.BusinessException;
import com.unitech.drinks.mapper.CategoryMapper;
import com.unitech.drinks.mapper.DrinkMapper;
import com.unitech.drinks.model.Category;
import com.unitech.drinks.model.Drink;
import com.unitech.drinks.service.DrinkService;
import com.unitech.drinks.vo.ResponseDrink;
import com.unitech.drinks.vo.ResponsePageDrinks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MysqlDrinkService implements DrinkService {

    @Autowired
    private DrinkMapper drinkMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public ResponsePageDrinks listDrinks(Integer page, Integer size) {
        //所有分类
        Map<Long, Category> categoryMap = new HashMap<>();
        categoryMapper.selectAll()
                .forEach(e -> categoryMap.put(e.getId(), e));
        //查询饮品
        PageHelper.startPage(page, size);
        List<Drink> drinks = drinkMapper.selectAll();



        List<ResponseDrink> responseDrinks = drinks.stream()
                .map(e -> ResponseDrink.converter(e, categoryMap))
                .collect(Collectors.toList());

        return ResponsePageDrinks.converter(new PageInfo<ResponseDrink>(responseDrinks));
    }

    @Override
    public Drink showDrink(Integer id) {
        Drink existsDrink = drinkMapper.selectByPrimaryKey(id);
        if (existsDrink == null) {
            throw new BusinessException(BusinessErrorCode.DRINK_NOT_FOUND);
        }
        return existsDrink;
    }

    @Override
    public Drink createDrink(Drink drink) {
        //查询是否有同名饮品
        Example example = new Example(Drink.class);
        example.createCriteria().andEqualTo("name", drink.getName().trim());
        List<Drink> drinks = drinkMapper.selectByExample(example);
        if (drinks.size() > 0) {//如果存在 抛出异常
            throw new BusinessException(BusinessErrorCode.DRINK_EXISTS);
        }
        drinkMapper.insert(drink);
        return drink;
    }

    @Override
    public Drink modifyDrink(Drink drink) {
        Drink exitsDrink = drinkMapper.selectByPrimaryKey(drink.getId());
        if (exitsDrink == null) { // 不存在抛出业务错误
            throw new BusinessException(BusinessErrorCode.DRINK_NOT_FOUND);
        }
        return drink;
    }

    @Override
    public void deleteDrink(Integer id) {
        Drink drink = drinkMapper.selectByPrimaryKey(id);
        if (drink == null) {
            throw new BusinessException(BusinessErrorCode.DRINK_NOT_FOUND);
        }
        drinkMapper.deleteByPrimaryKey(id);


    }
}
